﻿using System;
using System.Text;

namespace BfLib.Text.Html
{
    public class TagParser
    {
        private StringBuilder _sb;
        private char quoteSingle = '\'', quoteDouble = '"';
        private char quoteChar, nonQuoteChar;


        public TagParser()
        {
            this._sb = new StringBuilder();
        }

        public string GetAttibute(string tag, string attrib)
        {
            int i=0, j=0;

            if((tag==null) || (attrib==null)) return string.Empty;
            if ((attrib.Length == 0)||(tag.Length == 0)) return string.Empty;

            tag = reducesAttributeSpaces(tag);
            i = tag.IndexOf(String.Format("{0}=", attrib));

            if (i < 0)
            {
                return string.Empty;
            }
            else
            {
                i = i + attrib.Length;
            }

            if ((tag[i + 1] == quoteSingle) || (tag[i + 1] == quoteDouble))
            {
                quoteChar = tag[i + 1];
                if (quoteChar == quoteSingle)
                    nonQuoteChar = quoteDouble;
                else nonQuoteChar = quoteSingle;

                j = i + 2;
                while ((tag[j] != quoteChar) && (j < tag.Length) && (tag[j] != '>') && (tag[j] != nonQuoteChar))
                {
                    _sb.Append(tag[j]);
                    j++;
                }
            }
            else
            {
                j = i + 1;
                while ((tag[j] != ' ') && (j < tag.Length) && (tag[j] != '>'))
                {
                    _sb.Append(tag[j]);
                    j++;
                }
            }

            return _sb.ToString();
        }

        private string reducesAttributeSpaces(string s)
        {
            s = s.Replace("\t", string.Empty);
            while (s.IndexOf("   ") >= 0)
            {
                s = s.Replace("   ", " ");
            }
            while (s.IndexOf("  ") >= 0)
            {
                s = s.Replace("  ", " ");
            }

            while (s.IndexOf("= ") >= 0)
            {
                s = s.Replace("= ", "=");
            }
            while (s.IndexOf(" =") >= 0)
            {
                s = s.Replace(" =", "=");
            }

            return s;

        }

    }
}
